#define _CRT_SECURE_NO_WARNINGS 1
//**************************************************************************
//用二分查找，找到数组中的某一个数据。
//因为二分查找需要有序数组
//所以先排序，再查找
#include<stdio.h>
void bubbleSort(int arr[], int n)//冒泡排序
{
	int i = 0, j = 0, temp = 0;//定义双循环变量，临时变量用于交换
	for (i = 0; i < n - 1; i++)
	{
		for (j = 0; j < n - 1 - i; j++)
		{
			if (arr[j] > arr[j + 1])//前大于后，交换位置实现从小到大排序
			{
				temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}
int erfen(int arr[], int n,int key)//二分查找
{
	int left = 0;
	int right = n - 1;
	while (left<=right)
	{
		int mid = left + (right - left) / 2;
		if (arr[mid] > key)//去左边找
		{
			right = mid - 1;
		}
		else if (arr[mid] < key)//去右边找
		{
			left = mid + 1;
		}
		else//找到了
		{
			return mid;
			break;
		}

	}
		return -1;
}
void myPrint(int arr[],int  n)//打印
{
	int i = 0;
	for (i = 0; i < n; i++)
	{
		printf("%d ", arr[i]);
	}
	printf("\n");
}
int main()
{
	int arr[10] = { 1, 35, 3, 4, 56, 6, 24, 8, 99, 10 };
	int n = sizeof(arr) / sizeof(arr[0]);
	printf("已知数组：\n");
	myPrint(arr, n);
	int key,mid;
	printf("请输入要查找的元素:");
	scanf("%d", &key);
	printf("二分查找需要有序数组，重排后：\n");
	bubbleSort(arr, n);
	myPrint(arr, n);
	mid=erfen(arr, n,key);
	if(mid!=-1)
	printf("找到了%d的下标为%d\n",key, mid);
	else
	printf("未找到");
}
